﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace NBlog.Web.Application.Service.Internal.Caching
{
    public interface ICacheProvider
    {
        object Get(string cacheKey);
        void Add(string cacheKey, object item, DateTime absoluteExpiration);
        void Reset();
    }

    public class HttpContextCacheProvider : ICacheProvider
    {
        public object Get(string cacheKey)
        {
            return HttpContext.Current.Cache.Get(cacheKey);
        }

        public void Reset()
        {
            StringBuilder builder = new StringBuilder();
            List<string> lines = new List<string>();
            var enumerator = HttpContext.Current.Cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                HttpContext.Current.Cache.Remove(enumerator.Key.ToString());
                lines.Add(string.Format("{0} - clear.<br/>", enumerator.Key));
            }
            lines.Sort();
            lines.ForEach(str => builder.Append(str));
            HttpContext.Current.Response.Write(builder.ToString());
        }

        public void Add(string cacheKey, object item, DateTime absoluteExpiration)
        {
            HttpContext.Current.Cache.Add(cacheKey, item, null, absoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
    }
}